package com.main.by.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.main.by.entity.vo.NewsInfoVO;
import com.main.by.exception.ServiceException;
import com.main.by.service.NewsInfoService;
import com.main.by.service.UploadFileService;

@Controller
@RequestMapping("/adminjsp/newsInfo")
public class NewsInfoController {
	
	private Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	private NewsInfoService newSInfoService;
	
	@Autowired
	private UploadFileService uploadFileService;
	
	@RequestMapping(value = "", method = RequestMethod.POST)
	@ResponseBody 
	public void  addNewsInfo(HttpServletRequest request,HttpServletResponse response,@RequestParam("minPic") MultipartFile file1,@RequestParam("maxPic") MultipartFile file2) throws IOException{
		NewsInfoVO newsInfo = new NewsInfoVO();
		PrintWriter out = response.getWriter();
		logger.info("newsUpload info:");
		boolean flag = false;
		//errorMessage：上传失败，则是错误信息；上传成功，则提示成功以及显示文件上传后的地址
		String errorMessage = "";  
		try{
			String destinationDir ="G:/byProject/byProject/webapp/uploadFile/";
			List<MultipartFile> file = new ArrayList<MultipartFile>();
			file.add(file1);
			file.add(file2);
			String writeDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=UTF-8");
			String newsTitle = request.getParameter("newsTitle");
			String newsAuth = request.getParameter("newsAuth");
			String mainKey = request.getParameter("mainKey");
			String newsContent = request.getParameter("newsContent");
			newsInfo.setNewsTitle(newsTitle);
			newsInfo.setNewsAuth(newsAuth);
			newsInfo.setMainKey(mainKey);
			newsInfo.setNewsContent(newsContent);
			newsInfo.setNewsDate(writeDate);
			if (file.size() >= 2) {
				//获得文件的后缀名
				String file1Type = file.get(0).getContentType();
				String name1Type = file1Type.substring(file1Type.indexOf("/")+1,file1Type.length());
				String file2Type = file.get(1).getContentType();
				String name2ype = file2Type.substring(file2Type.indexOf("/")+1,file2Type.length());
				if (("jpg".equals(name1Type) ||"bmp".equals(name1Type) || "gif".equals(name1Type) || "jpeg".equals(name1Type)) &&
						("jpg".equals(name2ype) || "bmp".equals(name2ype) || "gif".equals(name2ype) || "jpeg".equals(name2ype)) ){
					String fileName1Type = file.get(0).getOriginalFilename();
					String fileName2Type = file.get(1).getOriginalFilename();
					String fileName1 = getFileName()+"1"+fileName1Type.substring(fileName1Type.indexOf("."),fileName1Type.length()); 
					String fileName2 = getFileName()+"2"+fileName2Type.substring(fileName2Type.indexOf("."),fileName2Type.length()); 
					newsInfo.setMinPic(fileName1);
					newsInfo.setMaxPic(fileName2);
					flag = uploadFileService.uploadHandoutImg(destinationDir,  file, fileName1,fileName2);
					if (flag) {
						flag = newSInfoService.addNewSInfo(newsInfo, request, response);
					} else {
						//上传失败，返回到前台
						out
						.print("<script type='text/javascript'>alert('上传失败');history.go(-1);</script>");
					}
					
				} else {
					out
					.print("<script type='text/javascript'>alert('不是标准的图片文件')</script>");
				}
			}
		}catch (ServiceException serviceE){
			logger.error("firstUpload failed!" , serviceE);
			errorMessage = serviceE.getMessage();
		}catch (Exception e){
			logger.error("firstUpload failed!" , e);
			errorMessage = "新增文件失败!";
		}
		if(flag){
		    //上传成功，返回到前台
			response.sendRedirect("newsList");
		} else {
			//上传失败，返回到前台
			out
			.print("<script type='text/javascript'>alert('上传失败');history.go(-1);</script>");
		}
			

	}
	
	private String getFileName() {
		//根据时间产生文件名
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmssms");
		return df.format(new Date());
	}
	

}
